<template>
    <div class="pubcontainer">
        <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="标题：">
      <el-input  placeholder="请输入标题内容..."  v-model="form.title" />
    </el-form-item>
    <el-form-item label="类别：">
      <el-select v-model="form.category" placeholder="请选择帖子类别">
        <el-option label="体育" value="1" />
        <el-option label="音乐" value="2" />
        <el-option label="学习" value="3" />
      </el-select>
    </el-form-item>
    <!-- 富文本编辑器 -->
    <div style="border: 1px solid #ccc">
      <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
      />
      <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
    </div>

    <el-form-item>
      <el-button class="publishbtn" type="primary" @click="onSubmit">发布</el-button>
    </el-form-item>
</el-form>
</div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { toast } from '@/composables/utils';
import { publishpost } from '@/apis/post';
import { useRouter } from 'vue-router';

const router = useRouter()


const form = ref({
    title:'',
    category:'',
})

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('')

// 模拟 ajax 异步获取内容
onMounted(() => {
    setTimeout(() => {
    }, 1500)
})

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const mode = 'default' // 或 'simple'

function onSubmit() {
    // 首先校验数据

    if (form.value.title.length === 0) {
        toast('请输入标题', 'error')
        return
    }
    if (form.value.category.length === 0) {
        toast('请选择类别', 'error')
        return
    }
    if (valueHtml.value.length === 0) {
        toast('请输入内容', 'error')
        return
    }
    console.log("数据校验通过！");
    publishpost({
        title:form.value.title,
        category:form.value.category,
        content:valueHtml.value
    }).then(res=>{
        console.log(res);
        form.value.title = ''
        form.value.category = ''
        valueHtml.value = ''
        toast("发布成功！", "success");
        // 跳转到首页
        router.replace('/')
    })
}
</script>

<style>
.publishbtn{
    width: 100%;
    margin-top: 20px;
}
.pubcontainer{
    width: 600px;
    margin: 0 auto;
}
</style>